<template>
  <!-- 添加或修改岗位对话框 -->
  <div class="conetr">
    <div class="center-board">
      <div class="center-title">
        <h3>模版-图文展示</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button icon="Download" type="success" plain @click="submitForm">保存文章</el-button>
        <!-- <el-button class="copy-btn-main" icon="DocumentCopy" type="primary" text @click="copy">
                复制代码
                </el-button> -->
        <el-button class="delete-btn" icon="Delete" plain type="danger" @click="empty">
          清空
        </el-button>
      </div>
    </div>
    <!-- <el-dialog :title="dialogTitle" v-model="dialogVisible" width="1000px" append-to-body @close="handleClose"> -->
    <el-form ref="formRef" :model="cmsArticle" :rules="rules" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="cmsArticle.title" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item v-if="hasCategory" label="分类" prop="categoryId">
        <SelectCategory
          v-model:modelValue="cmsArticle.categoryId"
          @update:modelValue="handleCategoryId"
        />
      </el-form-item>
      <el-form-item label="上传主图" prop="image">
        <ImageUpload v-model="cmsArticle.image" :limit="1" />
        <!-- <MultiImageUpload v-model="cmsArticle.image" /> -->
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="cmsArticle.sort" :min="1" :max="1000" />
      </el-form-item>
      <el-form-item label="内容" prop="normalArticleContent" required>
        <el-input
          v-model="cmsArticle.normalArticleContent"
          placeholder="请输入内容"
          type="textarea"
          :rows="10"
        />
      </el-form-item>
      <el-scrollbar height="150px">
        <el-form-item label="上传图片" prop="imageList">
          <ImageUpload v-model="cmsArticle.imageList" :limit="10" />
        </el-form-item>
      </el-scrollbar>
    </el-form>
  </div>
  <!-- <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template> -->
  <!-- </el-dialog> -->
</template>
<script setup>
import { ref, watch } from "vue";
const { proxy } = getCurrentInstance();
import { articleTemplateType, articleTypeTitleEnum } from "@/utils/enums/article";
import { typeIdEnum } from "@/utils/articleConfig";
import { addArticle, updateArticle } from "@/api/article";
import SelectCategory from "../selectCategory/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";

// 1. 正确定义 props
const props = defineProps({
  // 1 是装修知识的type固定字段 2是装修案例
  type: {
    type: String,
    required: true,
    default: "",
  },
  defaultData: {
    type: Object,
    default: null,
  },
  dialogShow: {
    type: Boolean,
    required: true,
    default: false,
  },
  hasCategory: {
    type: Boolean,
    default: true,
  },
});
const isEdit = ref(false); // 如果有默认值就是编辑
// const typeTitle = ref('')
const dialogTitle = ref("");
// 2. 定义组件内部的对话框显示状态
const dialogVisible = ref(false);

// 3. 监听父组件传入的 dialogShow
watch(
  () => props.dialogShow,
  (newVal) => {
    dialogVisible.value = newVal;
    isEdit.value = !!props.defaultData;
    // typeTitle.value = articleTypeTitleEnum[props.type]
    dialogTitle.value = isEdit.value ? `编辑-图文展示模版` : `添加-图文展示模版`;
  }
);

// 4. 定义 emit 以便向父组件通知状态变化

const emit = defineEmits(["update:dialogShow", "refreshList", "backTo"]);

// 5. 关闭对话框时通知父组件
const handleClose = () => {
  dialogVisible.value = false;
  emit("update:dialogShow", false);
};
const handleCategoryId = (categoryId) => {
  cmsArticle.value.categoryId = categoryId;
};
const cmsArticle = ref({
  title: "",
  sort: 1,
  type: props.type,
  templateType: articleTemplateType.IMAGE_TEXT, // 图文
  imageList: [],
  image: [],
});

const rules = ref({
  title: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { min: 3, max: 100, message: "长度在 3 到 100 个字符", trigger: "blur" },
  ],
  image: [{ required: true, message: "请上传主图", trigger: "change" }],
  imageList: [{ required: true, message: "请上传图片", trigger: "change" }],
  sort: [{ required: true, message: "请输入分类排序", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
  text: [{ required: true, message: "请输入活动形式", trigger: "blur" }],
  normalArticleContent: [{ required: true, message: "请输入内容", trigger: "blur" }],
});

function backTo() {
  emit("backTo");
}
const submitForm = async () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      await handleSubmitData();
    }
  });
};

const handleSubmitData = async () => {
  let blocks = cmsArticle.value.imageList.map((item, index) => {
    let one = {
      text: item.url,
      type: typeIdEnum.picture,
      sort: index + 1,
    };
    if (item.id) {
      one.id = item.id;
    }
    return one;
  });
  let oneblock = {
    text: cmsArticle.value.normalArticleContent,
    type: typeIdEnum.text,
    sort: cmsArticle.value.imageList.length + 1,
  };
  if (cmsArticle.value.normalArticleId) {
    oneblock.id = cmsArticle.value.normalArticleId;
  }
  blocks.push(oneblock);
  console.log(blocks, cmsArticle.value);
  let params = {
    title: cmsArticle.value.title,
    sort: cmsArticle.value.sort,
    categoryId: cmsArticle.value.categoryId,
    type: props.type,
    templateType: articleTemplateType.IMAGE_TEXT, // 图文
    image: JSON.stringify(cmsArticle.value.image), // 单独处理图片形式
    blocks: blocks,
  };
  if (props.defaultData?.id) {
    params.id = props.defaultData.id;
    methodUpdateArticle(params);
  } else {
    methodAddArticle(params);
  }
};
// 新增文章
async function methodAddArticle(params) {
  try {
    await addArticle(params);
    ElMessage.success("新增成功");
    backTo();
  } catch (err) {
    console.log(err);
  } finally {
    console.log("finally");
  }
}
// 修改文章
async function methodUpdateArticle(params) {
  console.log(params);
  try {
    await updateArticle(params);
    ElMessage.success("修改成功");
    // emit('backTo')
    backTo();
    // handleClose()
  } catch (err) {
    console.log(err);
  } finally {
    console.log("finally");
  }
}
const addEditArticleFunc = async (params, method) => {
  try {
    if (props.defaultData) {
      await updateArticle(params);
    } else {
      await addArticle(params);
    }
    proxy.$modal.msgSuccess("成功");
    // emit('backTo')
    backTo();
  } catch (err) {
    console.log(err);
  } finally {
    console.log("finally");
    dialogVisible.value = false;
  }
};
/**
 * 编辑文章的值处理
 */
const editDefaultData = () => {
  cmsArticle.value.id = props.defaultData.id;
  cmsArticle.value.title = props.defaultData.title;
  cmsArticle.value.sort = props.defaultData.sort;
  cmsArticle.value.categoryId = props.defaultData.categoryId;
  cmsArticle.value.image = JSON.parse(props.defaultData.image);
  props.defaultData.blocks.forEach((item) => {
    handleDefaultDataFunc(item);
  });
};
const handleDefaultDataFunc = (item) => {
  if (item.type === typeIdEnum.picture) {
    cmsArticle.value.imageList.push({
      name: item.text,
      url: item.text,
      id: item.id,
    });
  }
  if (item.type === typeIdEnum.text) {
    cmsArticle.value.normalArticleId = item.id; // 块的id
    cmsArticle.value.normalArticleContent = item.text;
  }
};
const resetData = () => {
  cmsArticle.value = {
    title: "",
    sort: 1,
    categoryId: 1,
    type: props.type,
    normalArticleContent: "",
    imageList: [],
    image: [],
  };
};
watch(
  () => dialogVisible.value,
  (newVal) => {
    resetData();
    if (!!newVal && props.defaultData) {
      editDefaultData();
    }
  }
);
const cancel = () => {
  dialogVisible.value = false;
};
function empty() {
  ElMessageBox.confirm("确定要清空所有组件吗？", "提示", { type: "warning" }).then(() => {
    cmsArticle.value = {};
  });
}
onMounted(() => {
  if (props.defaultData) {
    editDefaultData();
  }
});
</script>
<style scoped lang="scss">
.conetr {
  padding: 10px;
  background-color: #fff;
  position: relative;
  flex: 1;
  margin-left: 10px;
  box-sizing: border-box;
  background-color: #fff;
  padding: 10px 20px;

  .center-board {
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }
  }
}
</style>
